﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Zero.CheckPoint
{
    public enum SpawnDirection
    {
        Left = -1,
        Right = 1
    }


    public class CheckPoint : MonoBehaviour
    {
        public SpawnDirection playerSpawnDirection = SpawnDirection.Right;

        private bool _isActivated = false;

        private Collider2D _collider2D;
        private SpriteRenderer _spriteRenderer;


        private void Start()
        {
            _collider2D = GetComponent<Collider2D>();
            _spriteRenderer = GetComponent<SpriteRenderer>();
        }

        public void Spawn(GameObject player)
        {
            // 将玩家刚体速度重置
            var rigidbody2D = player.GetComponent<Rigidbody2D>();
            rigidbody2D.velocity = Vector2.zero;

            // 设置玩家位置
            player.transform.position = transform.position;

            // 设置玩家面向
            var localScale = player.transform.localScale;
            localScale.x = playerSpawnDirection == SpawnDirection.Left
                ? -Mathf.Abs(localScale.x)
                : Mathf.Abs(localScale.x);
            player.transform.localScale = localScale;
        }

        private void OnTriggerEnter2D(Collider2D other)
        {
            // 已经激活过不需要再激活
            if (_isActivated) return;


            if (other.CompareTag("Player"))
            {
                _isActivated = true;
                var playerController = other.GetComponent<PlayerController>();
                playerController.checkPoint = this;

                _collider2D.enabled = false;
                _spriteRenderer.material.color = Color.yellow;

                Debug.Log("玩家激活了存档点");
            }
        }
    }
}